<template>
  <view class="container">
    <view class="header">
     <view class="header-left" @click="goBack">
        <!-- <uni-icons type="left" size="28" color="#333"></uni-icons> -->
      </view>
      <text class="header-title"></text>
      <view class="header-right" @click="addBanner">
        <uni-icons type="plus" size="28" color="#333"></uni-icons>
      </view>
    </view>
    
    <view class="content">
      <!-- 轮播图列表 -->
      <view class="banner-list">
        <view v-for="(banner, index) in banners" :key="banner._id" class="banner-item">
          <view class="banner-info">
            <image :src="banner.imageUrl" mode="aspectFill" class="banner-image" />
            <view class="banner-details">
              <text class="banner-title">{{ banner.title || '未设置标题' }}</text>
              <text class="banner-description">{{ banner.description || '无描述' }}</text>
              <view class="banner-meta">
                <text class="link-info">
                  链接类型：{{ getLinkTypeText(banner.linkType) }}
                </text>
                <text class="sort-info">排序：{{ banner.sort || 0 }}</text>
              </view>
            </view>
          </view>
          
          <view class="banner-actions">
            <view class="status-switch">
              <text>启用：</text>
              <switch 
			          :checked="banner.status" 
                @change="toggleStatus($event,banner)"
                size="32"
              />
            </view>
            <view class="action-buttons">
              <button class="edit-btn" size="mini" @click="editBanner(banner)">编辑</button>
              <button class="delete-btn" size="mini" type="warn" @click="deleteBanner(banner._id)">删除</button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="banners.length === 0" class="empty-state">
        <uni-icons type="none" size="80" color="#ccc"></uni-icons>
        <text class="empty-text">暂无轮播图数据</text>
        <button type="primary" @click="addBanner">添加轮播图</button>
      </view>
    </view>
    
    <!-- 编辑/添加轮播图弹窗 -->
    <uni-popup ref="popup" type="bottom" :animation="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ isEdit ? '编辑轮播图' : '添加轮播图' }}</text>
          <text class="popup-close" @click="closePopup">&times;</text>
        </view>
        
        <uni-forms ref="form" :model="formData" :rules="rules">
          <uni-forms-item label="标题" name="title">
            <uni-easyinput v-model="formData.title" placeholder="请输入轮播图标题"></uni-easyinput>
          </uni-forms-item>
          
          <uni-forms-item label="描述" name="description">
            <uni-easyinput v-model="formData.description" type="textarea" placeholder="请输入轮播图描述"></uni-easyinput>
          </uni-forms-item>
          
          <uni-forms-item label="图片" name="imageUrl">
            <view class="upload-area">
              <image v-if="formData.imageUrl" :src="formData.imageUrl" mode="aspectFill" class="preview-image" @click="previewImage(formData.imageUrl)"></image>
              <view v-else class="upload-placeholder">
                <uni-icons type="upload" size="40" color="#999"></uni-icons>
                <text class="upload-text">点击上传轮播图</text>
              </view>
              <button class="upload-btn" size="mini" @click="chooseImage">选择图片</button>
            </view>
          </uni-forms-item>
          
          <uni-forms-item label="链接类型" name="linkType">
            <uni-data-select
              v-model="formData.linkType"
              :localdata="linkTypes"
              placeholder="请选择链接类型"
            ></uni-data-select>
          </uni-forms-item>
          
          <uni-forms-item 
            v-if="formData.linkType === 'category'" 
            label="分类ID" 
            name="linkId"
          >
            <uni-easyinput v-model="formData.linkId" placeholder="请输入分类ID"></uni-easyinput>
          </uni-forms-item>
          
          <uni-forms-item 
            v-if="formData.linkType === 'detail'" 
            label="类型" 
            name="linkId"
          >
            <uni-easyinput v-model="formData.linkId" placeholder="请输入轮播图类型"></uni-easyinput>
          </uni-forms-item>
          
          <uni-forms-item 
            v-if="formData.linkType === 'page'" 
            label="页面路径" 
            name="linkUrl"
          >
            <uni-easyinput v-model="formData.linkUrl" placeholder="请输入页面路径"></uni-easyinput>
          </uni-forms-item>
          
          <uni-forms-item label="排序" name="sort">
            <uni-easyinput v-model.number="formData.sort" type="number" placeholder="请输入排序号"></uni-easyinput>
          </uni-forms-item>
        </uni-forms>
        
        <view class="popup-footer">
          <button type="default" @click="closePopup">取消</button>
          <button type="primary" @click="submitForm">{{ isEdit ? '保存' : '添加' }}</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
// uni-app中使用内置导航API，不需要Vue Router
const banners = ref([]);
const popup = ref(null);
const form = ref(null);
const isEdit = ref(false);
const loading = ref(false);

// 表单数据
const formData = reactive({
  _id: '',
  title: '',
  description: '',
  imageUrl: '',
  linkType: 'category',
  linkId: '',
  linkUrl: '',
  sort: 0,
  status: true
});

// 链接类型选项
const linkTypes = [
  { value: 'category', text: '分类' },
  { value: 'detail', text: '壁纸详情' },
  { value: 'page', text: '页面' }
];

// 表单验证规则
const rules = {
  title: {
    required: true,
    message: '请输入标题',
    trigger: ['blur', 'change']
  },
  imageUrl: {
    required: true,
    message: '请上传轮播图',
    trigger: ['blur', 'change']
  },
  linkType: {
    required: true,
    message: '请选择链接类型',
    trigger: ['blur', 'change']
  }
};

// 获取轮播图列表
const getBanners = async () => {
  loading.value = true;
  try {
    const res = await uniCloud.callFunction({
      name: 'adminBannerManager',
      data: { action: 'getList' }
    });
     console.log('获取轮播图res:', res);
    if (res.result && res.result.code === 200) {
      banners.value = res.result.data || [];
    } else {
      uni.showToast({
        title: res.result?.message || '获取轮播图失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取轮播图失败:', error);
    uni.showToast({
      title: '获取轮播图失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 获取链接类型文本
const getLinkTypeText = (type) => {
  const option = linkTypes.find(item => item.value === type);
  return option ? option.text : '未知';
};

// 添加轮播图
const addBanner = () => {
	console.log('添加轮播图',formData);
  isEdit.value = false;
  // 重置表单
  Object.assign(formData, {
    _id: '',
    title: '',
    description: '',
    imageUrl: '',
    linkType: 'category',
    linkId: '',
    linkUrl: '',
    sort: 0,
    status: true
  });
  popup.value.open();
};

// 编辑轮播图
const editBanner = (banner) => {
  isEdit.value = true;
  Object.assign(formData, { ...banner });
  popup.value.open();
};

// 关闭弹窗
const closePopup = () => {
  popup.value.close();
};

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed']
    });
    console.log('上传图片',res)
    if (res && res.tempFiles && res.tempFiles.length > 0) {
      const tempFilePath = res.tempFiles[0].tempFilePath;
      // 获取文件扩展名，增加错误处理
      const match = tempFilePath.match(/\.(\w+)$/);
      const extension = match ? match[1] : 'jpg'; // 默认为jpg
      
      // 上传图片到云存储
      const uploadRes = await uniCloud.uploadFile({
        cloudPath: `banners/${Date.now()}-${Math.random().toString(36).substring(2)}.${extension}`,
        filePath: tempFilePath
      });
      
      if (uploadRes.fileID) {
        formData.imageUrl = uploadRes.fileID;
      } else {
        uni.showToast({
          title: '上传图片失败',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('选择图片失败:', error);
  }
};

// 预览图片
const previewImage = (imageUrl) => {
  uni.previewImage({
    urls: [imageUrl]
  });
};

// 提交表单
const submitForm = async () => {
	console.log('提交表单formData',formData);
	console.log('form.value',form.value);
  // if (!form.value) return ;
  
  // form.value.validate(async (valid) => {
    // if (valid) {
      try {
        const action = isEdit.value ? 'update' : 'add';
        const res = await uniCloud.callFunction({
          name: 'adminBannerManager',
          data: {
            action,
            ...formData
          }
        });
        
        if (res.result && res.result.code === 200) {
          uni.showToast({
            title: isEdit.value ? '更新成功' : '添加成功',
            icon: 'success'
          });
          closePopup();
          getBanners();
        } else {
          uni.showToast({
            title: res.result?.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('操作失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
  //   }
  // });
};

// 切换状态
const toggleStatus = async (e,banner) => {
	 banner.status = e.detail.value;
  try {
    const res = await uniCloud.callFunction({
      name: 'adminBannerManager',
      data: {
        action: 'updateStatus',
        _id: banner._id,
        status: banner.status
      }
    });
    
    if (res.result && res.result.code !== 200) {
      // 恢复原状态
      banner.status = !banner.status;
      uni.showToast({
        title: res.result?.message || '更新状态失败',
        icon: 'none'
      });
    }
  } catch (error) {
    // 恢复原状态
    banner.status = !banner.status;
    console.error('更新状态失败:', error);
    uni.showToast({
      title: '更新状态失败',
      icon: 'none'
    });
  }
};

// 删除轮播图
const deleteBanner = async (id) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个轮播图吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uniCloud.callFunction({
            name: 'adminBannerManager',
            data: {
              action: 'delete',
              _id: id
            }
          });
          
          if (result.result && result.result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            getBanners();
          } else {
            uni.showToast({
              title: result.result?.message || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期
onMounted(() => {
  getBanners();
});
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  height: 90rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  .header-left,
  .header-right {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.content {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.banner-list {
  .banner-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    .banner-info {
      display: flex;
      margin-bottom: 20rpx;
      .banner-image {
        width: 200rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      .banner-details {
        flex: 1;
        .banner-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
          display: block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .banner-description {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 8rpx;
          display: block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .banner-meta {
          display: flex;
          justify-content: space-between;
          .link-info,
          .sort-info {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
    .banner-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .status-switch {
        display: flex;
        align-items: center;
        text {
          font-size: 28rpx;
          color: #666;
          margin-right: 10rpx;
        }
      }
      .action-buttons {
        display: flex;
        gap: 10rpx;
        .edit-btn {
          background-color: #409eff;
          color: #fff;
        }
        .delete-btn {
          background-color: #f56c6c;
          color: #fff;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin: 20rpx 0;
  }
}

.popup-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: 30rpx;
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
    .popup-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 0 10rpx;
    }
  }
  .upload-area {
    position: relative;
    width: 100%;
    height: 200rpx;
    border: 1rpx dashed #ddd;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10rpx;
    .preview-image {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
    }
    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .upload-text {
        font-size: 28rpx;
        color: #999;
        margin-top: 10rpx;
      }
    }
    .upload-btn {
      position: absolute;
      bottom: 10rpx;
      right: 10rpx;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
    }
  }
  .popup-footer {
    display: flex;
    padding: 20rpx;
    gap: 20rpx;
    button {
      flex: 1;
    }
  }
}
</style>